package com.chihb.domain;

import com.alibaba.fastjson.annotation.JSONField;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author chihb
 * @create-time 2024/11/29 9:47
 * @description
 */
@Data
@NoArgsConstructor
public class LoginUser implements UserDetails {

    // 用以封装用户信息
    private User user;

    // 该登入用户的所有权限集合 -- 权限标识符
    private List<String> permissions;

    public LoginUser(User user, List<String> permissions) {
        this.user = user;
        this.permissions = permissions;
    }

    //存储SpringSecurity所需要的权限信息的集合
    @JSONField(serialize = false) // 不序列化该字段
    private List<GrantedAuthority> authorities;

    // 获取权限集合 -- 授权 -- 该方法就是为前面的鉴权
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        // 将List<String> permissions转为Collection<? extends GrantedAuthority>
        List<GrantedAuthority> list = new ArrayList<>();
        for (String permission : permissions) {
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority(permission);
            list.add(authority);
        }
        return list;
    }

    // 用户名
    @Override
    public String getUsername() {
        return user.getUserName();
    }
     // 用户的加密后的密码， 不加密会使用{noop}前缀
    @Override
    public String getPassword() {
        return user.getPassword();
    }

    // 帐户未过期
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    // 帐户未锁定
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    // 凭证是否过期
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    // 用户是否可用
    @Override
    public boolean isEnabled() {
        return true;
    }
}
